// 提交链接 https://leetcode.cn/problems/amount-of-time-for-binary-tree-to-be-infected/submissions/526682783/
// 2385 感染二叉树需要的总时间
// 完成日期： 2024.10.7
// 树状dp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, vector<int>> ma;
    unordered_map<int, int> flag;
    int amountOfTime(TreeNode* root, int start) {
        slove(root);
        queue<pair<int, int>> que;
        vector<pair<int, int>> ans;
        que.push(pair<int, int>(start, 0));
        while (!que.empty())
        {
            pair<int, int> temp = que.front();
            ans.push_back(temp);
            flag[temp.first] = 1;
            for (auto& x : ma[temp.first])
            {
                if (flag[x]) continue;
                que.push(pair<int, int>(x, temp.second + 1));
            }
            que.pop();
        }
        return ans.back().second;
    }
    void slove(TreeNode* root)
    {
        if (!root) return;
        if (root->left)
        {
             ma[root->val].push_back(root->left->val);
             ma[root->left->val].push_back(root->val);
        }
        if (root->right)
        {
            ma[root->val].push_back(root->right->val);
            ma[root->right->val].push_back(root->val);
        }
        slove(root->left);
        slove(root->right);
        return;
    }
};